<template>
  <div class="dataInput">
    <!--绘制工具条-->
    <el-button-group>
      <el-button size="medium" class="el-icon-circle-plus-outline" @click="editDraw">绘制</el-button>
      <el-button size="medium" class="el-icon-edit-outline" @click="editInfo">录入</el-button>
      <el-button size="medium" class="el-icon-edit-outline" @click="uploadInfo">上传</el-button>
    </el-button-group>
    <!--坐标串-->
    <div class="div-coord-input-extras" v-show="isVisible===1">
      <i class="tab-pane-header-btn el-icon-close" @click="isVisible=0"></i>
      <el-scrollbar noresize>
        <el-row v-for="coordinate in coordinates" :key="coordinate.index">
          <el-col :span="20">
            <el-input
              placeholder="请输入坐标"
              clearable
              size="mini"
              @keyup.enter.native="coordinateAddSubmit()"
              type="text"
              v-model="coordinate.value"
            ></el-input>
          </el-col>
          <el-col :span="4">
            <el-button v-if="coordinate.isAdd"
                       :disabled="isGeoPoint"
                       class="kfb-icon-tianjia"
                       @click="addRow(coordinate)"
                       size="mini"
                       circle
                       style="padding: 5px;margin-right: 8px"
            ></el-button>
            <el-button
              v-if="!coordinate.isAdd"
              :disabled="isGeoPoint"
              class="kfb-icon-jianqu"
              @click="removeRow(coordinate)"
              size="mini"
              circle
              style="padding: 5px;margin-right: 8px"
            ></el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-button
              type="text"
              @click="coordinateAddSubmit"
              size="mini"
              :disabled="isEditable"
            >添加
            </el-button>
            <!--<el-button @click="coordinateAddCancel" size="mini" type="text">取消</el-button>-->
          </el-col>
        </el-row>
      </el-scrollbar>
    </div>
    <div class="dataInputByFile" v-show="isVisible===2">
      <i class="tab-pane-header-btn el-icon-close" @click="isVisible=0"></i>
      <el-row>
        <el-col :span="12">
          <el-button type="success" :disabled="isEditable" @click="downData" :loading="downloading">下载模板</el-button>
        </el-col>
        <el-col :span="12">
          <input
            ref="excel-upload-input"
            class="excel-upload-input"
            type="file"
            accept=".xlsx, .xls"
            @change="handleClick"
          >
          <el-button
            :loading="uploading"
            style="margin-left:0px;"
            size="mini"
            type="primary"
            @click="handleUpload"
            :disabled="isEditable"
          >数据上传
          </el-button>

        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
  import {mapState} from 'vuex';
  import {uuid} from '@/assets/js/utils/Uuid';
  import BoxUtil from '@/assets/js/utils/BoxUtil'
  import XLSX from "xlsx";
  import Excel from "@/assets/js/utils/Export2Excel";

  export default {
    data() {
      return {
        coordinates: [{value: "", isAdd: true}],
        isVisible: 0,
        downloading: false,
        uploading: false
      };
    },
    methods: {
      /**
       * 绘制点
       */
      editDraw() {
        if (!this.featureType) {
          this.$message.warning("请在左侧选中要编辑的要素服务!");
          return;
        }
        switch (this.featureType) {
          case '0':                     //点
            this.$store.state.sjwh.drawControl.changeMode('draw_point');
            break;
          case '1':                     //线
            this.$store.state.sjwh.drawControl.changeMode('draw_line_string');
            break;
          case '2':                     //面
            this.$store.state.sjwh.drawControl.changeMode('draw_polygon');
            break;
        }
      },
      /**
       * 手动录入点
       */
      editInfo() {
        if (!this.featureType) {
          this.$message.warning("请在左侧选中要编辑的要素服务!");
          return;
        }
        this.isVisible = this.isVisible === 1 ? 0 : 1;
        this.coordinates = [{value: "", isAdd: true}];
      },
      /**
       * 上传信息
       */
      uploadInfo() {
        this.isVisible = this.isVisible === 2 ? 0 : 2;
      },
      /**
       * 校验
       */
      validate($event) {
        let reg = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)\,-?((0|[1-8]?[0-9]?)(([.][0-9]{1,4})?)|90(([.][0]{1,4})?))$/;
        // if (!reg.test($event)) {
        //   this.$message.error("该行数据格式不匹配!");
        //   return false;
        // }
        return true;
      },
      /**
       * 提交
       */
      coordinateAddSubmit() {

      },
      /**
       * 添加一行
       * @param item
       */
      addRow(item) {
        if (this.validate(item.value)) {   //校验
          this.$set(item, 'isAdd', false);
          this.coordinates.splice(0, 0, {value: "", isAdd: true});
        }
      },
      /**
       * 删除一行
       * @param item
       */
      removeRow(item) {
        this.coordinates.splice(this.coordinates.indexOf(item), 1);
      },
      /**
       * 浏览excel文件
       */
      handleUpload() {
        this.$refs["excel-upload-input"].click();
      },
      /**
       * 开始上传
       */
      handleClick(e) {
        this.uploading = true;
        const files = e.target.files;
        const rawFile = files[0]; // only use files[0]
        if (!rawFile) return;
        this.upload(rawFile);
      },
      /**
       * 上传数据
       */
      upload(rawFile) {
        this.$refs["excel-upload-input"].value = null; // fix can't select the same excel
        this.readerData(rawFile);
      },
      /**
       * 渲染数据
       */
      readerData(rawFile) {
      
      },
      /**
       * 获取首字段
       */
      getHeaderRow(sheet) {
        const headers = [];
 
        return headers;
      },
      /**
       * 是否是excel
       */
      isExcel(file) {
        return /\.(xlsx|xls|csv)$/.test(file.name);
      },
      /**
       * 上传处理数据
       */
      processExcelData(worksheet) {
      
      },

      /**
       * 转坐标串
       */
      componentCoordinate(c) {
        if (c === '') return false;
        const zb = c.split(',');
        let all = [];
        let a = [];
        for (let i = 0; i < zb.length; i++) {
          a[i % 2] = zb[i];
          if (i % 2 === 1) {
            all.push(a);
            a = [];
          }
        }
        return all;
      },


      /**
       * 下载数据
       */
      downData() {
        this.downloading = true;
        let tHeader = ["ID", "XY"];//
        let tempHeader = ["UserID", "XY"];//必须字段
        const attr = JSON.parse(this.attributes);
        for (let k in attr) {
          tHeader.push(attr[k]);
          tempHeader.push(k);
        }
        const data = this.allFeatureCollection.map(o => {
          return tempHeader.map(f => {
            if (f === "XY") {
              return o.geometry.coordinates;
            }
            return o.properties[f];
          })
        })
        Excel.export_json_to_excel({
          header: tHeader,
          data,  //{ID:1,lon:126,lat:45} [1,126,45]
          filename: name,
          autoWidth: this.autoWidth
        });
        this.downloading = false;
      }
    },
    computed: {
      ...
        mapState({
          featureType(state) {
            return state.sjwh.selectFeature ? state.sjwh.selectFeature.type : undefined;
          },

          isEditable(state) {
            return !state.sjwh.selectFeature;
          },
          /**
           * 属性字段
           * @param state
           */
          attributes(state) {
            return state.sjwh.selectFeature ? state.sjwh.selectFeature.attribute : {}
          },
          /**
           * 临时存当前选中的服务的要素几何
           */
          allFeatureCollection(state) {
            return state.sjwh.featureCollection;
          },
          /**
           * 要素字段类型
           */
          fieldsType(state) {
            return state.sjwh.featureFields;
          }
        }),
      /**
       * 要素类型
       * @returns {string|{required: boolean, message: string, trigger: string}[]|*}
       */
      isGeoPoint() {
        return this.featureType ? this.featureType === '0' : undefined;
      }
    }
  }
</script>
<style lang="scss">
  .excel-upload-input {
    display: none;
    z-index: -9999;
  }

  .dataInput {
    position: absolute;
    top: 10px;
    right: 80px;
    z-index: 999;
  }

  .font-extras {
    font-size: 14px;
  }

  .div-coord-input-extras {
    position: absolute;
    right: 0;
    top: 48px;
    width: 250px;
    background-color: #ffffff;
  }

  .div-coord-input-extras .el-scrollbar {
    max-height: 400px;
    overflow-y: inherit;
  }

  .div-coord-input-extras .el-row {
    margin-top: 5px;
    margin-left: 5px;
  }

  .div-coord-input-extras .el-button {
    float: right;
    margin-right: 2px;
  }

  .add_coord {
    position: relative;
    color: #409eff;
    cursor: pointer;
    margin: 5px 5px;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
  }

  .dataInputByFile {
    position: absolute;
    right: 0;
    top: 48px;
    width: 250px;
    background-color: #ffffff;
  }

  .dataInputByFile .el-row {
    margin-top: 5px;
    margin-left: 5px;
  }

  .dataInputByFile .el-button {
    padding: 9px 15px;
    font-size: 12px;
    margin-left: 15px;
  }

  .tab-pane-header-btn {
    position: absolute;
    right: -19px;
    margin: 10px;
    top: -20px;
    font-size: 16px;
    transition: transform 0.3s;
    background-color: #f44336;
    border-radius: 10px;
    color: #fff;
    padding: 2px;
    z-index: 900;
    cursor: pointer;
  }
</style>
